/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package backend;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import db.UserDAO;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 *
 * @author brook
 */
@ManagedBean(name = "LoginBean")
@RequestScoped
public class LoginBean {

    private static final String INVALID = "Invalid login credentials";
    String email;
    String password;
    int authority;
    
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    public int getAuthorty() {
        return authority;
    }

    public void setAuthorty(int authority) {
        this.authority = authority;
    }
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public LoginBean() {
    }

    public void login() throws Exception {
        //UserDAO email = UserDAO.loginUser(this.email, this.password);
        UserDAO user = UserDAO.loginUser(this.email, this.password);
        //UserDAO authority = UserDAO.extractUser(null)
        if (user != null && user.authority== 0) {            
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", user);
            FacesContext.getCurrentInstance().getExternalContext().redirect("./app/home.xhtml");
        } 
        else if(user != null && user.authority == 1){
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", user);
            FacesContext.getCurrentInstance().getExternalContext().redirect("./app/admin.xhtml");
        }
        else {
            FacesContext.getCurrentInstance().addMessage("username", new FacesMessage(INVALID, INVALID));
        }
    }
}
